/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.samples.jfinal.config;

import com.luter.heimdall.core.authorization.store.AuthorizationStore;
import com.luter.heimdall.core.authorization.store.MemoryCachedAuthorizationStore;
import com.luter.heimdall.core.context.WebContextHolder;
import com.luter.heimdall.core.manager.AuthenticationManager;
import com.luter.heimdall.core.manager.HeimdallAuthenticationManager;
import com.luter.heimdall.core.manager.HeimdallAuthorizationManager;
import com.luter.heimdall.core.token.store.MemoryCachedTokenStore;
import com.luter.heimdall.core.token.store.TokenStore;
import com.luter.heimdall.samples.jfinal.service.AuthorityDataProviderImpl;
import com.luter.heimdall.starter.jfinal.context.JFinalWebContextHolder;
import org.slf4j.Logger;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 创建认证授权管理器
 *
 * @author luter
 */
public abstract class HeimdallManagerCreator {
    private static final transient Logger log = getLogger(HeimdallManagerCreator.class);

    public static HeimdallAuthorizationManager initManager() {
        //Web上下文
        WebContextHolder contextHolder = new JFinalWebContextHolder();
        //权限缓存 采用 内存缓存
        AuthorizationStore authorizationStore = new MemoryCachedAuthorizationStore(new AuthorityDataProviderImpl());
        //TokenStore 采用 内存缓存
        TokenStore tokenStore = new MemoryCachedTokenStore().authorizationStore(authorizationStore);
        //认证管理器
        AuthenticationManager authenticationManager =
                new HeimdallAuthenticationManager(contextHolder).tokenStore(tokenStore);
        log.warn("=========AuthenticationManager initialized successfully");
        //授权管理器
        final HeimdallAuthorizationManager authorizationManager =
                new HeimdallAuthorizationManager(authorizationStore, authenticationManager);

        log.warn("=========AuthorizationManager initialized successfully");
        return authorizationManager;
    }
}
